<?php

define('ADMIN_PATH', './');
define('MAIN_PATH', '../');

/* Load the Core */
//require_once(MAIN_PATH . 'init.' . pathinfo(__FILE__, PATHINFO_EXTENSION));

class Loader
{
	public $base;
	
	public $loader;
	
	public $ajax;

	public $auth_admin_username;
	private $auth_id;
	public $data;
	public $dashboard = null;
	
	public $display;
	
	function __construct()
	{
		$this->base = SmitBase::getInstance();
		require_once './Display' . EXT;
		require_once './Ajax' . EXT;
		
		$this->display = new Display;
		$this->ajax = new Ajax;
	}

	function session_is_valid()
	{
		if(!isset($_COOKIE[$this->base->db->config['cookie_prefix'] . 'super_session']))
		{
			return false;
		}
		$ipaddress = substr($_SERVER['REMOTE_ADDR'], 0, 255);
		$useragent = substr($_SERVER['HTTP_USER_AGENT'], 0, 255);
		
		//SQL::exec('SELECT * FROM ' . SQL::$prefix . 'dashboard_sessions WHERE sid = \'' . SQL::escape($_COOKIE[Config::get('cookie_prefix') . 'super_session']) . '\' AND address = \'' . $ipaddress . '\' AND useragent = \'' . $useragent . '\'');
		$where = array(
			'sid' => $_COOKIE[$this->base->db->config['cookie_prefix'] . 'super_session'],
			'address' => $ipaddress,
			'useragent' => $useragent
		);
		$this->base->db->select()->from('dashboard_sessions')->where($where)->limit(1)->run();
		if($this->base->db->num_rows() == 1)
		{
			$this->data = $this->base->db->result();
			$this->auth_id = $this->base->db->row('user_id');
			$this->auth_admin_username = $this->get_admin_username();
			
			$this->base->db->select()->from('dashboard_data')->run();
			$this->dashboard = new Stdclass;
			foreach($this->base->db->result() as $dataset)
			{
				$this->dashboard->{$dataset->key} = $dataset->value;
			}
			return true;
		}
		else
		{
			$this->base->lib->setcookie('super_session', '', time() - (60*60*24*100));
			return false;
		}
	}
	function get_admin_username($id = '')
	{
		if(strlen(trim($id)) == 0)
		{	
			$this->base->db->select('*')->from('users')->where('id', intval($this->auth_id))->limit(1)->run();
			return $this->base->db->row('username');
		}
		else
		{
			$this->base->db->select('*')->from('users')->where('id', intval($id))->limit(1)->run();
			return $this->base->db->row('username');
		}
	}
	
	function valid_query($string)
	{
		return (bool) preg_match('/^[a-zA-Z0-9_]+$/', $string);
	}
	
	function log_login_attempt($username, $success = 0)
	{
		$this->base->db->insert('dashboard_login_logs', array(
			'username' => $username,
			'ipaddress' => substr($this->base->lib->input_server('REMOTE_ADDR'), 0, 255),
			'time' => $this->base->lib->timestamp(),
			'success' => $success
		));
	}
	
	function platform_info($complete = 0)
	{
		$sapi = PHP_SAPI;
		$string = '<a href="'.$this->uri('diagnostics').'" title="PHPInfo">PHP ' . PHP_VERSION . '</a>';
		$os = $this->get_os();
		if(!strstr($sapi, 'apache') || $complete == 1)
		{
			$string .= ' (' . ((substr($sapi, 0, 3) == 'cgi') ? 'cgi' : $sapi) . ')';
		}
		$string .= ' ' . $os;
		
		return $string;
	}
	
	function get_os()
	{
		$os = strtolower(PHP_OS);
		if(substr($os, 0, 3) == 'win')
		{
			$os = 'Windows';
		}
		elseif($os == 'darwin')
		{
			$os = 'Mac OS X';
		}
		elseif(strstr($os, 'linux'))
		{
			$os = 'Linux';
		}
		elseif(strstr($os, 'bsd'))
		{
			$os = 'BSD';
		}
		elseif(strstr($os, 'sun'))
		{
			$os = 'Solaris';
		}
		else
		{
			$os = 'Unknown';
		}
		$string = $os . ' ' . php_uname('m');
		return $string;
	}
	function get_latest_info()
	{
		/*if(!file_exists(ADMIN_PATH . 'version.xml'))
		{
		}*/
		$file_time = filemtime(ADMIN_PATH . 'version.xml');
		$next = $file_time + (7 * 24 * 60 * 60);
		if($next <= time())
		{
			$contents = file_get_contents(ADMIN_PATH . 'version2.xml');
			if(!is_writable(ADMIN_PATH . 'version.xml'))
			{
				chmod(ADMIN_PATH . 'version.xml', 0666);
			}
			file_put_contents(ADMIN_PATH . 'version.xml', $contents);
		}
		$xml = simplexml_load_file(ADMIN_PATH . 'version.xml');
		$parts = (string) $xml->current->build[0];
		$day = substr($parts, 0, 2);
		$year = substr($parts, -2, 2);
		$passed = substr($parts, 2, 1);
		return array('name' => $xml->current->human[0], 'build' => (int) $xml->current->build[0], 'day' => $day, 'year' => $year, 'passed' => $passed);
	}
	function get_server_load() {
		if(substr(strtolower(PHP_OS), 0, 3) != 'win') {
			if(file_exists('/proc/loadavg')) {
				$load = file_get_contents('/proc/loadavg');
				$load = explode(' ', $load);
				return $load[0];
			}
			elseif(function_exists('shell_exec')) {
				$load = explode(' ', `uptime`);
				return $load[count($load)-1];
			}
			else {
				return FALSE;
			}
		}
		else {
			if(class_exists('COM')) {
				$wmi = new COM('WinMgmts:\\\\.');
				$cpus = $wmi->InstancesOf('Win32_Processor');

				$cpuload = 0;
				$i = 0;
				foreach($cpus as $cpu) {
					$cpuload += $cpu->LoadPercentage;
					$i++;
				}

				$cpuload = round($cpuload / $i, 2);
				return $cpuload;
			}
			else {
				return FALSE;
			}
		}
	}
	function uri($controller, $parts = '')
	{
		if(is_array($controller))
		{
			$parts = http_build_query($controller);
			$controller = '';
		}
		elseif(is_string($controller))
		{
			$controller = 'com=' . $controller;
			if(is_array($parts))
			{
				$parts = '&' . http_build_query($parts);
			}
		}
		return $this->base->vars['root']['root_url'] . SMIT_CP . '/index.php?' . $controller . $parts;
	}
}
?>